<?php
	if (sizeof($_GET) == 4)
	{

		$id = $_GET['id'];
		$key = $_GET['key'];
		$hun = $_GET['hun'];
		$code = $_GET['code'];

		// check if size H(un) == 40 and code == 40 	
		$passed = true;
		if (strlen(trim($hun)) != 40)
		{
			echo "Error: the hash value of the username must be exactly 40 characters!<br />";
			$passed = false;
		}
		if (strlen(trim($code)) != 40)
		{
			echo "Error: the hash value of the code must be exactly 40 characters!";
			$passed = false;
		}
		if (!($passed))
		{
			exit();
		}

		// if passed then connect to db
		$mysqli = new mysqli('localhost', 'root', 'project3', 'implauth');
		if ($mysqli->connect_errno)
		{
			echo "Error: Database connection error!";
			exit();
		}
		
		// if passed then validate the id and key
		$res = $mysqli->query("select count(*) as total from servers where id like '$id' and secretkey like '$key'");
		$ob = $res->fetch_object();
		$res->close();
		if ($ob->total != 1)
		{
			echo "Error: Either the id and/or key did not match!";
			$mysqli->close();
			exit();
		}

		// if passed then check for code collision
		$res = $mysqli->query("select count(*) as total from accountstba where code like '$code'");
		$ob = $res->fetch_object();
		$res->close();
		if ($ob->total != 0)
		{
			echo 1;
			$mysqli->close();
			exit();
		}
		
		// if passed then check whether hun is waiting to be activated for the id
		$res = $mysqli->query("select count(*) as total from accountstba where serverid like '$id' and hun like '$hun'");
		$ob = $res->fetch_object();
		$res->close();
		if ($ob->total == 1)
		{
			echo "Error: This username has been added and is waiting to be activated!";
			$mysqli->close();
			exit();
		}

		// if passed then check whether H(un) is a duplicate for the id and key 
		$res = $mysqli->query("select count(*) as total from accounts where serverid like '$id' and hun like '$hun'");
		$ob = $res->fetch_object();
		$res->close();
		if ($ob->total == 1) // yes, == is correct
		{
			echo "Error: This username has already been added!";
			$mysqli->close();
			exit();
		}
		
		// if passed then insert into db
		$res = $mysqli->query("insert into accountstba values ('$id', '$code', '$hun')");
		if (!($res))
		{
			echo "Error: Cannot insert into table!";
			$mysqli->close();
			exit();
		}
		
		// if passed then echo 0 and close db
		echo 0;
		$mysqli->close();

	}
	else
	{
		echo "Error: Invalid number of arguments specified!";
	}

?>
